package cn.jiedanba.cacert.common.ca.encryption;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import cn.jiedanba.cacert.common.bc.base.BaseSecurity;

/**
 * SM4
 * 
 * @author dell
 *
 */
public class SM4Util extends BaseSecurity {

	private static final String ENCODING = "UTF-8";
	public static final String ALGORITHM_NAME = "SM4";
	// 加密算法/分组加密模式/分组填充方式
	// PKCS5Padding-以8个字节为一组进行分组加密
	// 定义分组加密模式使用：PKCS5Padding
	public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
	// 128-32位16进制；256-64位16进制
	public static final int DEFAULT_KEY_SIZE = 128;

	/**
	 * 生成ECB暗号
	 * 
	 * @explain ECB模式（电子密码本模式：Electronic codebook）
	 * @param algorithmName
	 *            算法名称
	 * @param mode
	 *            模式
	 * @param key
	 * @return
	 * @throws Exception
	 */
	private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
		Cipher cipher = Cipher.getInstance(algorithmName, BC);
		Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
		cipher.init(mode, sm4Key);
		return cipher;
	}

	/**
	 * 自动生成密钥
	 * 
	 * @explain
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 */
	public static byte[] generateKey() {
		try {
			return generateKey(DEFAULT_KEY_SIZE);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("生成密钥异常");
		}
	}

	/**
	 * 生成指定长度密钥
	 * 
	 * @explain
	 * @param keySize
	 * @return
	 * @throws Exception
	 */
	public static byte[] generateKey(int keySize) throws Exception {
		KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BC);
		kg.init(keySize, new SecureRandom());
		return kg.generateKey().getEncoded();
	}

	/**
	 * 加密模式之Ecb
	 * 
	 * @explain
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptEcb(String key, byte[] data) {
		try {
			Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE,
					Base64.decodeBase64(key));
			return cipher.doFinal(data);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("SM4加密异常");
		}
	}

	/**
	 * 解密
	 * 
	 * @explain
	 * @param cipher
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptEcb(String key, byte[] ecrypt) {
		try {
			Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE,
					Base64.decodeBase64(key));
			return cipher.doFinal(ecrypt);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("SM4解密异常");
		}
	}

}
